package com.sgu6.sgu6_machine.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sgu6.serialport.dto.DeviceDto;
import com.sgu6.sgu6_machine.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ComAdapter extends RecyclerView.Adapter implements View.OnClickListener {

    private List<DeviceDto> deviceDtos;
    private Context mContext;

    public ComAdapter(Context mContext, List<DeviceDto> deviceDtos) {
        this.deviceDtos = deviceDtos;
        this.mContext = mContext;
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.item_com_select, viewGroup, false);
        v.setOnClickListener(this);
        return new Holder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
        holder.itemView.setTag(i);
        if (holder instanceof Holder) {
            ((Holder) holder).tvComName.setText("[" + deviceDtos.get(i).getName() + "]");
            ((Holder) holder).tvComPath.setText("[" + deviceDtos.get(i).getRoot() + "]");
            String readAuthority = deviceDtos.get(i).getFile().canRead() ? "可读" : "不可读";
            String whiteAuthority = deviceDtos.get(i).getFile().canRead() ? "可写" : "不可写";
            String executeAuthority = deviceDtos.get(i).getFile().canExecute() ? "可执行" : "不可执行";
            ((Holder) holder).tvComAuthority.setText("[" + readAuthority + whiteAuthority + executeAuthority + "]");
//            if (deviceDtos.get(i).isSelected()) {
//                ((Holder) holder).llBackground.setBackgroundResource(android.R.color.darker_gray);
//            } else {
//                ((Holder) holder).llBackground.setBackground(null);
//            }
        }
    }

    @Override
    public int getItemCount() {
        return deviceDtos.size();
    }

    @Override
    public void onClick(View v) {
        listener.onItemClick(v, (int) v.getTag());
    }


    static class Holder extends RecyclerView.ViewHolder {
        @BindView(R.id.tvComName)
        TextView tvComName;
        @BindView(R.id.tvComPath)
        TextView tvComPath;
        @BindView(R.id.tvComAuthority)
        TextView tvComAuthority;
        @BindView(R.id.ll_background)
        LinearLayout llBackground;


        Holder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }

    public void setOnClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
}
